package com.willie.boot.rabbit.demo.producer;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.MessageProperties;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * <p>
 * 消息生产者
 * </p>
 *
 * @author willie
 * @since 2019/3/15
 */
public class RabbitProducer {
    //交换机名称
    private static final String EXCHANGE_NAME = "exchange_demo";
    //路由键
    private static final String ROUTING_KEY = "routingkey_demo";
    // 对列名称
    private static final String QUEUE_NAME = "hey";
    //主机地址
    private static final String HOST = "192.168.10.50";

    public static void main(String[] args) throws IOException, TimeoutException {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(HOST);
        Connection connection = factory.newConnection();
        //创建信道
        Channel channel = connection.createChannel();
        //创建一个direct类型的交换机
        channel.exchangeDeclare(EXCHANGE_NAME, "direct", true, false, null);
        //创建一个队列
        channel.queueDeclare(QUEUE_NAME, true, false, false, null);
        //绑定交换机和队列路由规则
        channel.queueBind(QUEUE_NAME, EXCHANGE_NAME, ROUTING_KEY);
        String message = "Hello World";
        //发布消息，指定路由规则
        channel.basicPublish(EXCHANGE_NAME, ROUTING_KEY, MessageProperties.PERSISTENT_TEXT_PLAIN, message.getBytes());
        channel.close();
        connection.close();
    }
}
